package com.tanhua.dubbo.api;

import com.tanhua.domain.mongo.*;
import com.tanhua.domain.vo.PageResult;
import org.apache.commons.lang3.RandomUtils;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserLikeApiImpl implements UserLikeApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 查询用户喜欢了多少人
     *
     * @param userId 用户id
     * @return userId喜欢的人的数量
     */
    @Override
    public long queryLikeCount(long userId) {
        Query query = new Query(Criteria.where("userId").is(userId));
        return mongoTemplate.count(query, UserLike.class);
    }

    /**
     * 查询用户有多少粉丝（有多少人喜欢这个用户）
     *
     * @param userId 用户id
     * @return 粉丝数量
     */
    @Override
    public long queryFansCount(long userId) {
        Query query = new Query(Criteria.where("likeUserId").is(userId));
        return mongoTemplate.count(query, UserLike.class);
    }

    /**
     * 查询好友数量（相互喜欢）
     *
     * @param userId 用户id
     * @return 好友数量
     */
    @Override
    public long queryFriendsCount(long userId) {
        Query query = new Query(Criteria.where("userId").is(userId));
        return mongoTemplate.count(query, Friend.class);
    }

    /**
     * 分页查询好友列表（相互喜欢列表）
     *
     * @param userId   用户id
     * @param page     页码
     * @param pagesize 查询几条
     * @return 分页结果
     */
    @Override
    public PageResult<CommonLikeUser> queryFriendsList(Long userId, int page, int pagesize) {
        Query query = new Query(Criteria.where("userId").is(userId))
                .with(Sort.by(Sort.Order.desc("created")))
                .with(PageRequest.of(page - 1, pagesize));
        List<Friend> list = mongoTemplate.find(query, Friend.class);
        List<CommonLikeUser> likeUserList = new ArrayList<>();
        for (Friend friend : list) {
            CommonLikeUser user = new CommonLikeUser();
            user.setTargetUserId(friend.getFriendId());
            user.setScore(queryScore(userId, friend.getFriendId()));
            likeUserList.add(user);
        }
        long count = mongoTemplate.count(query, Friend.class);
        int pages = (int) Math.ceil(count * 1.0 / pagesize);
        return new PageResult<>((int) count, pagesize, pages, page, likeUserList);
    }

    /**
     * 分页查询喜欢的用户列表
     *
     * @param userId   用户id
     * @param page     页码
     * @param pagesize 查询几条
     * @return 分页结果
     */
    @Override
    public PageResult<CommonLikeUser> queryLikeList(Long userId, int page, int pagesize) {
        Query query = new Query(Criteria.where("userId").is(userId))
                .with(Sort.by(Sort.Order.desc("created")))
                .with(PageRequest.of(page - 1, pagesize));
        List<UserLike> userLikes = mongoTemplate.find(query, UserLike.class);
        long count = mongoTemplate.count(query, UserLike.class);

        List<CommonLikeUser> likeUserList = new ArrayList<>();
        for (UserLike userLike : userLikes) {
            CommonLikeUser user = new CommonLikeUser();
            user.setTargetUserId(userLike.getLikeUserId());
            user.setScore(queryScore(userId, userLike.getLikeUserId()));
            likeUserList.add(user);
        }
        int pages = (int) Math.ceil(count * 1.0 / pagesize);
        return new PageResult<>((int) count, pagesize, pages, page, likeUserList);
    }

    /**
     * 分页查询粉丝列表
     *
     * @param userId   用户id
     * @param page     页码
     * @param pagesize 查询几条
     * @return 分页结果
     */
    @Override
    public PageResult<CommonLikeUser> queryFansList(Long userId, int page, int pagesize) {
        Query query = new Query(Criteria.where("likeUserId").is(userId))
                .with(Sort.by(Sort.Order.desc("created")))
                .with(PageRequest.of(page - 1, pagesize));
        List<UserLike> userLikes = mongoTemplate.find(query, UserLike.class);
        long count = mongoTemplate.count(query, UserLike.class);

        List<CommonLikeUser> likeUserList = new ArrayList<>();
        for (UserLike userLike : userLikes) {
            CommonLikeUser user = new CommonLikeUser();
            user.setTargetUserId(userLike.getUserId());
            user.setScore(queryScore(userId, userLike.getUserId()));
            likeUserList.add(user);
        }
        int pages = (int) Math.ceil(count * 1.0 / pagesize);
        return new PageResult<>((int) count, pagesize, pages, page, likeUserList);
    }

    /**
     * 分页查询来访者
     *
     * @param userId   用户id（被访问者）
     * @param page     页码
     * @param pagesize 查询几条
     * @return 分页结果
     */
    @Override
    public PageResult<CommonLikeUser> findVisitorList(Long userId, int page, int pagesize) {
        Query query = new Query(Criteria.where("userId").is(userId))
                .with(Sort.by(Sort.Order.desc("date")))
                .with(PageRequest.of(page - 1, pagesize));
        List<Visitor> visitorList = mongoTemplate.find(query, Visitor.class);
        long count = mongoTemplate.count(query, Visitor.class);

        List<CommonLikeUser> likeUserList = new ArrayList<>();
        for (Visitor visitor : visitorList) {
            CommonLikeUser user = new CommonLikeUser();
            user.setTargetUserId(visitor.getVisitorUserId());
            user.setScore(queryScore(userId, visitor.getVisitorUserId()));
            likeUserList.add(user);
        }
        int pages = (int) Math.ceil(count * 1.0 / pagesize);
        return new PageResult<>((int) count, pagesize, pages, page, likeUserList);
    }

    /**
     * 删除对某一用户的喜欢
     *
     * @param userId     用户id
     * @param likeUserId 将要取消喜欢的用户id
     */
    @Override
    public void delete(Long userId, Long likeUserId) {
        Query query = new Query(Criteria.where("userId").is(userId).and("likeUserId").is(likeUserId));
        mongoTemplate.remove(query, UserLike.class);
    }

    @Override
    public void save(UserLike userLike) {
        mongoTemplate.save(userLike);
    }


    /**
     * 查询两个用户之间的缘分值
     *
     * @param userId       用户id
     * @param targetUserId 目标用户id
     * @return 缘分值得分
     */
    public Double queryScore(long userId, long targetUserId) {
        Query query = new Query(Criteria.where("toUserId").is(userId).and("userId").is(targetUserId));
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);
        if (recommendUser != null) {
            return recommendUser.getScore();
        }
        return RandomUtils.nextDouble(70, 95);
    }

    /**
     * 单向喜欢
     *
     * @param userId
     * @param likeUserId
     */
    @Override
    public String singleLove(Long userId, Long likeUserId) {
        Query query = new Query(Criteria.where("userId").is(userId).and("likeUserId").is(likeUserId));
        if (mongoTemplate.count(query, UserLike.class) > 0) {
            return null;
        }
        UserLike userLike = new UserLike();
        userLike.setId(ObjectId.get());
        userLike.setUserId(userId);
        userLike.setLikeUserId(likeUserId);
        userLike.setCreated(System.currentTimeMillis());
        save(userLike);
        return userLike.getLikeUserId().toString();
    }

    /**
     * 查询粉丝用户是否存在
     *
     * @param userId
     * @param likeUserId
     * @return
     */
    @Override
    public UserLike userList(Long userId, Long likeUserId) {
        Query query = new Query(Criteria.where("userId").is(userId).and("likeUserId").is(likeUserId));
        return mongoTemplate.findOne(query, UserLike.class);
    }
}
